﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MS_UI
{
    public partial class FrmProtocolConfig : Form
    {
        public FrmProtocolConfig()
        {
            InitializeComponent();
          
            this.Load += FrmProtocolConfig_Load;
         
        }
        
        private void FrmProtocolConfig_Load(object sender, EventArgs e)
        {
            //端口
            for (int i = 0; i < 20; i++)
            {
                this.Port.Items.Add("COM" + i);
            }
            //波特率
            this.Paud.Items.AddRange(new string[] { "4800","9600","14400",
                "19200","38400"
            });
            //校验位
            this.Parity.Items.AddRange(new string[] { "None", "Odd", "Even" });
            //地址位
            for (int i = 0; i < 20; i++)
            {
                this.Address.Items.Add(i.ToString());
            }
            //数据位
            this.DataBits.Items.AddRange(new string[] { "7", "8" });
            //停止位
            this.StopBits.Items.AddRange(new string[] { "1", "2" });
            foreach (Control i in this.groupBox1.Controls)
            {
                if (i is ComboBox)
                {
                    ComboBox j = i as ComboBox;
                    j.SelectedIndex = 1;
                }
            }
            this.Parity.SelectedIndex = 0;
            this.StopBits.SelectedIndex = 0;
        }
        string ModbusPath = Application.StartupPath + @"\ConfigFile";
     
        private void button1_Click(object sender, EventArgs e)
        {
            Directory.CreateDirectory(ModbusPath);

            using (FileStream fs = new FileStream(ModbusPath + @"\MODBUS.ini", FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                using (StreamWriter sw = new StreamWriter(fs))
                {
                    try
                    {
                        foreach (Control i in this.groupBox1.Controls)
                        {
                            if (i is ComboBox)
                            {
                                ComboBox j = i as ComboBox;
                                sw.WriteLineAsync(j.Text.ToString());
                            }
                        }
                        MessageBox.Show("保存文件成功！");
                    }
                    catch(Exception es)
                    {
                        MessageBox.Show(es.Message);
                        MessageBox.Show("保存文件失败！");
                    }
                    
                    
                }
            }
          
        }

        private void button1_MouseMove(object sender, MouseEventArgs e)
        {
            button1.Cursor = Cursors.Hand;
        }
    }
}
